<?php

namespace App\Observers;

use App\Models\User;
use App\Models\Inspection;
use Illuminate\Support\Facades\Log;

class UserObserver
{
	protected function setInviteCodeBeforeCreating(User $user)
	{
		if (! $user->invite_code) {
			$user->invite_code = random_number(10, $user, 'invite_code');

			// Generate invite code failed.
			if (! $user->invite_code) return false;
		}
	}

    public function creating(User $user)
    {
	    $this->setInviteCodeBeforeCreating($user);
    }

    public function deleted(User $user)
    {
	    $parent = $user->parent;
	    if ($parent and $parent->children->isEmpty()) {
		    $parent->update(['is_parent' => false]);
	    }

	    $user->delFromCache();
    }

	public function saving(User $user)
	{
		$user->name = strip_tags(clean($user->name, 'default'));
		$user->nickname = strip_tags(clean($user->nickname, 'default'));
		$user->signature = strip_tags(clean($user->signature, 'default'));

		
	}

    public function saved(User $user)
    {
        if ($user->is_locked) {
            $user->delFromCache();
        } else {
            $user->addToCache();
            //$user->setRank();
        }
    }
}
